package com.zhentao.studyim.controller;

import com.zhentao.studyim.dto.ApiResponse;
import com.zhentao.studyim.dto.LoginRequest;
import com.zhentao.studyim.dto.RegisterRequest;
import com.zhentao.studyim.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 处理用户登录、注册、退出等请求
 */
@RestController                    // REST风格控制器
@RequestMapping("/api/auth")       // 请求路径前缀
@RequiredArgsConstructor          // 自动生成构造函数
@CrossOrigin(origins = "*")       // 允许跨域请求
public class AuthController {

    private final UserService userService;

    /**
     * 用户注册接口
     * POST /api/auth/register
     */
    @PostMapping("/register")
    public ApiResponse<Map<String, Object>> register(@Validated @RequestBody RegisterRequest request) {
        try {
            Map<String, Object> result = userService.register(request);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 用户登录接口
     * POST /api/auth/login
     */
    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@Validated @RequestBody LoginRequest request) {
        try {
            Map<String, Object> result = userService.login(request);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 用户退出登录接口
     * POST /api/auth/logout
     */
    @PostMapping("/logout")
    public ApiResponse<Void> logout(@RequestHeader("Authorization") String token) {
        // 这里应该从token中解析用户ID，简化处理
        return ApiResponse.success(null);
    }

    /**
     * 获取用户列表接口
     * GET /api/auth/users
     */
    @GetMapping("/users")
    public ApiResponse<java.util.List<com.zhentao.studyim.entity.User>> getUserList() {
        try {
            java.util.List<com.zhentao.studyim.entity.User> users = userService.getAllUsers();
            return ApiResponse.success(users);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 数据库状态检查接口
     * GET /api/auth/db-status
     */
    @GetMapping("/db-status")
    public ApiResponse<Map<String, Object>> getDatabaseStatus() {
        try {
            Map<String, Object> status = new HashMap<>();
            
            // 获取用户总数
            java.util.List<com.zhentao.studyim.entity.User> users = userService.getAllUsers();
            status.put("totalUsers", users.size());
            
            // 获取最近注册的用户
            java.util.List<Map<String, Object>> recentUsers = new java.util.ArrayList<>();
            users.stream()
                .sorted((u1, u2) -> u2.getCreateTime().compareTo(u1.getCreateTime()))
                .limit(5)
                .forEach(u -> {
                    Map<String, Object> userMap = new HashMap<>();
                    userMap.put("id", u.getUserId());
                    userMap.put("username", u.getUsername());
                    userMap.put("nickname", u.getNickname());
                    userMap.put("createTime", u.getCreateTime().toString());
                    recentUsers.add(userMap);
                });
            status.put("recentUsers", recentUsers);
            
            status.put("timestamp", java.time.LocalDateTime.now().toString());
            
            return ApiResponse.success(status);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}